package cn.school.mybatis.servlet;

import cn.school.mybatis.Util.SpringMButil;
import cn.school.mybatis.pojo.Grade;
import cn.school.mybatis.pojo.Student;
import cn.school.mybatis.service.GradeService;
import cn.school.mybatis.service.StudentService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//通配符的请求地址
@WebServlet("*.do")
public class StudentMainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().print("login action");
//		request.setCharacterEncoding("utf-8");
//		String u = request.getParameter("userName");
//		String p = request.getParameter("userPass");
//		Admin admin = adminService.login(u, p);
//		if (admin != null) {
//			HttpSession s = request.getSession();
//			s.setAttribute("USER_LOGIN", admin);
//
//			// 转发
//			request.getRequestDispatcher("/pages/welcome.jsp").forward(request, response);
//			return;
//		}
//
//		response.sendRedirect("pages/fail.jsp");

    }
    //更新学生信息
    protected void studentUpdate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        int stuid=0;
        String sname="";
        String sex="";
        String telephone="";
        String qq="";
        String wechat="";
        int gradeid =0;
        String enterdate="";
        String fromcity="";
        String birthday="";
        String address="";
        String pass="123456";
        String idcardpic="";

        //文件上传
        FileItemFactory item=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(item);
        upload.setHeaderEncoding("utf-8");
        List<FileItem> list= null;
        try {
            list = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        for(FileItem fi:list){
            if(fi.isFormField()){
                //普通的表单元素
//            out.print("<h2>"+fi.getFieldName()+":"+fi.getString("utf-8")+"</h2>");
                switch (fi.getFieldName()){
                    case "stuName":
                        sname=fi.getString("utf-8");
                        break;
                    case "stuSex":
                        sex=fi.getString("utf-8");
                        break;
                    case "stuPhone":
                        telephone=fi.getString("utf-8");
                        break;
                    case "stuQQ":
                        qq=fi.getString("utf-8");
                        break;
                    case "stuWechat":
                        wechat=fi.getString("utf-8");
                        break;
                    case "stuGrade":
                        gradeid=Integer.parseInt(fi.getString("utf-8"));
                        break;
                    case "enterTime":
                        enterdate=fi.getString("utf-8");
                        break;
                    case "stuBirth":
                        birthday=fi.getString("utf-8");
                        break;
                    case "fromCity":
                        fromcity=fi.getString("utf-8");
                        break;
                    case "stuAddr":
                        address=fi.getString("utf-8");
                        break;
                    case "stuid":
                        stuid=Integer.parseInt(fi.getString("utf-8"));
                        break;

                }

            }else{
                //文件
                if (fi.getSize()==0){
//                out.print("<h2>没有文件！</h2>");
                    continue;
                }
//            out.print("<h2>这是一个文件，文件名："+fi.getName()+"，元素名："+fi.getFieldName()+"</h2>");
                String path=this.getServletContext().getRealPath("images");
                //文件要换一个名字,保证后缀是相同
                String fName =fi.getName();
                String houZhui=fName.substring(fName.lastIndexOf("."));
                String fileName= UUID.randomUUID()+houZhui;
                File f=new File(path,fileName);
//            out.print(f.getAbsolutePath());
                idcardpic=fileName;
                try {
                    fi.write(f);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        Student student = new Student(stuid,sname, sex, telephone, qq, wechat, gradeid, enterdate, fromcity, birthday, address,pass,idcardpic);
//    out.print(student);

        int result = 0;
        try{
            StudentService studentService= SpringMButil.getBean(StudentService.class);

            result = studentService.update(student);
        }catch (Exception e){ out.println("信息修改失败...");e.printStackTrace();}

        if (result==1){
            out.println("<script>alert('"+result+"条信息修改成功！');location.replace('"+request.getContextPath()+"/WEB-INF/AdminLTEdemo01/s_student/s_studentInfo.jsp')</script>");

        }else {
            out.println("<script>alert('信息修改失败...');history.back(-1);</script>");

        }

    }
    //显示一个学生信息
    protected void studentInfoShow(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        int num = new Integer(request.getParameter("stuno"));
        StudentService studentService= SpringMButil.getBean(StudentService.class);

        Student student = studentService.get(num);
        if (student == null) {
            out.print("<script>alert('未找到相关信息！');history.back();</script>");
            return;
        }

        //年级名称
        GradeService gradeService= SpringMButil.getBean(GradeService.class);
        List<Grade> lists = gradeService.searchAll();
        String gradeName=lists.get(student.getGradeid()).getGname();

        request.setAttribute("student",student);
        request.setAttribute("gradeName",gradeName);

        request.getRequestDispatcher("/WEB-INF/AdminLTEdemo01/s_student/s_studentShow.jsp").forward(request,response);

    }
    //显示学生信息
    protected void studentInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int pageNo = 1;
        int pageSize = 15;
        int gradeid = 0;
        try {
            pageNo = Integer.parseInt(request.getParameter("pageNo"));
        } catch (Exception e) {
            pageNo = 1;
        }
        try {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            pageSize = 15;
        }
        try {
            gradeid = Integer.parseInt(request.getParameter("gradeid"));
        } catch (Exception e) {
            gradeid = 0;
        }
        //条件查询
        String sname = request.getParameter("sname");
        String telephone = request.getParameter("telephone");
        String wechat = request.getParameter("wechat");

        sname = sname == null ? "" : sname;
        telephone = telephone == null ? "" : telephone;
        wechat = wechat == null ? "" : wechat;

        Map<String, Object> map = new HashMap<>();
        map.put("sname", sname);
        map.put("telephone", telephone);
        map.put("wechat", wechat);
        map.put("gradeid", gradeid);
        StudentService studentService= SpringMButil.getBean(StudentService.class);

        List<Student> lists = studentService.search(pageNo, pageSize, map);
        //总条数
        double pageTotal = studentService.findTotal(map);
        //总页数
        int pageNum = (int) Math.ceil(pageTotal / pageSize);

        //获取年级名称
        GradeService gradeService= SpringMButil.getBean(GradeService.class);
        List<Grade> gradeList = gradeService.searchAll();
        Map gradeMap=new HashMap();
        for (Grade g:gradeList){
            int id= (int) g.getId();
            String gname=g.getGname();
            gradeMap.put(id,gname);
        }
        for (Student stu:lists){
            stu.setGname((String) gradeMap.get(stu.getGradeid()));
        }


//        req.setAttribute("pageNo",pageNo);
//        req.setAttribute("pageSize",pageSize);
//        req.setAttribute("pageTotal",(int) pageTotal);
//        req.setAttribute("pageNum",pageNum);
//        req.setAttribute("sname",sname);
//        req.setAttribute("telephone",telephone);
//        req.setAttribute("stuLists",lists);
//        req.getRequestDispatcher("/AdminLTEdemo01/s_student/s_studentInfo.jsp").forward(req,resp);

        //定义一个map对象存放json数据
        Map<String, Object> stuPage = new HashMap<>();
        stuPage.put("pageNo", pageNo);
        stuPage.put("pageSize", pageSize);
        stuPage.put("pageTotal", (int) pageTotal);
        stuPage.put("pageNum", pageNum);
        stuPage.put("sname", sname);
        stuPage.put("telephone", telephone);
        stuPage.put("stuDatas", lists);
        String stuPageJSON = JSON.toJSONString(stuPage, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNullNumberAsZero);

        System.out.println(stuPageJSON);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(stuPageJSON);
    }
    //增加学生信息
    protected void studentAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //        resp.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = resp.getWriter();
        request.setCharacterEncoding("utf-8");
        String sname="";
        String sex="";
        String telephone="";
        String qq="";
        String wechat="";
        int gradeid =0;
        String enterdate="";
        String fromcity="";
        String birthday="";
        String address="";
        String pass="123456";
        String idcardpic="";

        //文件上传
        FileItemFactory item=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(item);
        upload.setHeaderEncoding("utf-8");
        List<FileItem> list= null;
        try {
            list = upload.parseRequest(request);
            System.out.println(list);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        for(FileItem fi:list){
            if(fi.isFormField()){
                //普通的表单元素
//            out.print("<h2>"+fi.getFieldName()+":"+fi.getString("utf-8")+"</h2>");
                switch (fi.getFieldName()){
                    case "stuName":
                        sname=fi.getString("stuName");
                        break;
                    case "stuSex":
                        sex=fi.getString("stuSex");
                        break;
                    case "stuPhone":
                        telephone=fi.getString("stuPhone");
                        break;
                    case "stuQQ":
                        qq=fi.getString("stuQQ");
                        break;
                    case "stuWechat":
                        wechat=fi.getString("stuWechat");
                        break;
                    case "stuGrade":
                        gradeid=Integer.parseInt(fi.getString("stuGrade"));
                        break;
                    case "enterTime":
                        enterdate=fi.getString("enterTime");
                        break;
                    case "stuBirth":
                        birthday=fi.getString("stuBirth");
                        break;
                    case "fromCity":
                        fromcity=fi.getString("fromCity");
                        break;
                    case "stuAddr":
                        address=fi.getString("stuAddr");
                        break;

                }

            }else{
                //文件
                if (fi.getSize()==0){
//                out.print("<h2>没有文件！</h2>");
                    continue;
                }
//            out.print("<h2>这是一个文件，文件名："+fi.getName()+"，元素名："+fi.getFieldName()+"</h2>");
                String path= this.getServletContext().getRealPath("images");
                //文件要换一个名字,保证后缀是相同
                String fName =fi.getName();
                String houZhui=fName.substring(fName.lastIndexOf("."));
                String fileName= UUID.randomUUID()+houZhui;
                File f=new File(path,fileName);
//            out.print(f.getAbsolutePath());
                idcardpic=fileName;
                try {
                    fi.write(f);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Student student=new Student(sname,sex,telephone,qq,wechat,gradeid,enterdate,fromcity,birthday,address,pass,idcardpic);
        System.err.println(student);
        int result = 0;
        try{
            StudentService studentService= SpringMButil.getBean(StudentService.class);
            result = studentService.add(student);
        }catch (Exception e){}
        response.getWriter().print(result > 0 ? true : false);
    }

    //查找年级信息
    protected void gradeInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //        resp.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = resp.getWriter();
        GradeService gradeService= SpringMButil.getBean(GradeService.class);
        List<Grade> list = gradeService.searchAll();
        request.setAttribute("grades",list);
        request.getRequestDispatcher("/WEB-INF/AdminLTEdemo01/s_grade/s_gradeInfo.jsp").forward(request,response);
    }
    //检查微信号是否已存在
    protected void checkWechat(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String wechat = request.getParameter("wechat");
        StudentService studentService= SpringMButil.getBean(StudentService.class);
        boolean check=studentService.findWechat(wechat);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(check);
        System.out.println(check);
        out.flush();
        out.close();
    }
    //检查手机号是否已存在
    protected void checkTele(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String telephone = request.getParameter("telephone");
        StudentService studentService= SpringMButil.getBean(StudentService.class);
        boolean check = studentService.findTel(telephone);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(check);
        System.out.println(check);
        out.flush();
        out.close();
    }
    //
    protected void register(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().print("register action");
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getServletPath();
        String action = path.substring(1, path.length() - 3);
        try {
            if (action.equals("doGet") || action.equals("doPost") || action.equals("service")) {
                response.sendError(500, "非法请求");
                return;
            }
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class,
                    HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            response.getWriter().print("error=>" + e.getMessage());
            e.printStackTrace();
        }

        // if ("login".equals(action)) {
//			login(request, response);
//		} else if ("register".equals(action)) {
//			register(request, response);
//		} else if ("update".equals(action)) {
//			update(request, response);
//		} else {
//			response.getWriter().println("未知操作");
//		}

//		response.setContentType("text/html;charset=utf-8");
//		PrintWriter out = response.getWriter();
//		out.print("<html>");
//		out.print("<body>");
//		out.print("<h1>");
//		out.print("contextpath=" + request.getContextPath());
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("URI=" + request.getRequestURI());
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("URL=" + request.getRequestURL());
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("QueryString=" + request.getQueryString());
//		out.print("</h1>");
//		out.print("<h1 style='color:red'>");
//		out.print("servletpath=" + request.getServletPath());
//		out.print("</h1>");
//
//		out.print("<h1 style='color:red'>");
//		if ("login".equals(action)) {
//			out.println("执行登陆操作");
//			String u = request.getParameter("userName");
//
//		} else if ("register".equals(action)) {
//			out.println("执行注册操作");
//		} else if ("update".equals(action)) {
//			out.println("执行修改操作");
//		} else {
//			out.println("未知操作");
//		}
//		out.print("</h1>");
//
//		out.print("</body>");
//		out.print("</html>");
//		out.flush();
//		String action = request.getParameter("action");
//		if ("login".equals(action)) {
//			System.out.println("执行登陆操作");
//		} else if ("register".equals(action)) {
//			System.out.println("执行注册操作");
//		} else if ("update".equals(action)) {
//			System.out.println("执行修改操作");
//		} else {
//			System.out.println("未知操作");
//		}
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
